<?php
/**
 * Created by PhpStorm.
 * User: jason
 * Date: 2017/12/4
 * Time: 1:29
 */

namespace Home\Service;


use Think\Model;

class SearchKeywordsService extends Model
{
    /**
     * 记录用户搜索关键词
     * @param $keywords
     * @return bool
     */
    public function record($keywords)
    {
        if (!$keywords) {
            return false;
        }
        $time = strtotime(date('Y-m-d', time()));
        //关键词每天的分开记录
        foreach ($keywords as $key => $val) {
            $keyword = M('SearchKeywords')->where(['keyword' => $val, 'search_time' => $time])->find();
            if ($keyword) {
                M('SearchKeywords')->where(['keyword' => $val])->setInc('times');
            } else {
                $data = [
                    'keyword' => $val,
                    'search_time' => strtotime(date('Y-m-d', time()))
                ];
                M('SearchKeywords')->add($data);
            }
        }
        return true;
    }

    /**
     * 获取关键词搜索条件
     * @return array|bool|string
     */
    public function keywordsMap()
    {
        //取7天内的搜索记录
        $startTime = strtotime(date('Y-m-d', strtotime('-7 days', time()))); //7天前0点
        $endTime = time();

        $map = [
            'create_time' => ['between', $startTime.','.$endTime],
            'keyword'   => ['neq', '']
        ];
        $list = M('SearchKeywords')->where($map)
            ->field('keyword, sum(times) as sum')
            ->group('keyword')
            ->order('sum desc')
            ->select();

        if (!$list) {
            return false;
        }

        $map = '';
        foreach ($list as $key => $val) {
            $map['_string'] .= '(name like "%'. $val['keyword'] .'%") OR ';
        }
        
        //去除尾部的‘ OR ’
        $map['_string'] = substr($map['_string'], 0, strlen($map['_string'])-4);
        return $map;
    }
}